package com.lsk.admin.AdminSystem;

import com.jfinal.aop.Before;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import com.lsk.util.*;

import java.util.*;

/**
 * Created by Administrator on 2017/12/15 0015.
 */
public class AdminSystemService {
    Cache cache= Redis.use(PropKit.get("cache.name"));

    /**
     * 保存权限
     * @param map
     * @return
     */
    public ReturnData saveRule(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        try {
            String rules=map.get("rules")[0];
            String name=map.get("name")[0];
            String parentid=map.get("parentid")[0];
            Record record=new Record();
            record.set("name",name).set("type","button");
            record.set("url",rules).set("percode",rules);
            if ("".equals(parentid)==false){
                record.set("parentid",Integer.parseInt(parentid));
            }
            boolean result=Db.save("sys_permission",record);
            if (result){
                returnData.setCode("000000");
                returnData.setMsg("添加成功");
            }else {
                returnData.setCode("111111");
                returnData.setMsg("添加失败");
            }
        }catch (Exception e){
            returnData.setCode("111111");
            returnData.setMsg("添加异常 "+e);
            Syslog.error("添加权限异常"+e);
        }
        return returnData;
    }

    /**
     * 保存权限
     * @param id  权限ID
     * @param parentid 父ID
     * @param url URL
     * @param name 名称
     * @return
     */
    public ReturnData savePermissionService(String id,String parentid,String url,String name){
        boolean sa=false;
        if ("".equals(id) || id==null){//执行新增
            Record record=new Record().set("id",UtilUUID.getUUID()).set("url",url).set("name",name).set("type","menu");
            if ("".equals(parentid)==false){
                record.set("parentid",parentid);
            }
            sa=Db.save("sys_permission","id",record);
        }else {//执行修改
            Record record=new Record().set("url",url).set("name",name).set("type","menu").set("id",id);
            if ("".equals(parentid)==false){
                record.set("parentid",parentid);
            }
            sa=Db.update("sys_permission","id",record);
        }
        ReturnData returnData=new ReturnData();
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }
    /**
     * 权限列表
     */
    public ReturnData ruleList(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        String type=map.get("type")[0];//权限类型
        String url=map.get("url")[0];//url
        String name=map.get("name")[0];//名称
        int curr=Integer.parseInt(map.get("currentPage")[0]);//当前页
        int size=Integer.parseInt(map.get("limit")[0]);
        String sql="SELECT *from sys_permission where 1=1 ";
        if ("".equals(type)==false){//一级权限列表
            sql+=" and parentId ='"+type+"'";
        }else {
            sql+=" and  parentid ='0'";
        }
        if ("".equals(url)==false){
            sql+=" and url like '%"+url+"%'";
        }
        if ("".equals(name)==false){
            sql+=" and name like '%"+name+"%'";
        }
        PageUtil<List<Record>> pageUtil= new PageUtil<>(curr, size, sql);
        returnData.setData(pageUtil);
        return returnData;
    }
    /**
     * 查询所有一级菜单
     */
    public ReturnData topMenu(){
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from sys_permission WHERE parentid ='0' ";
        List<Record> list=Db.find(sql);
        returnData.setData(list);
        return returnData;
    }
    /**
     * 查询所有顶级部门
     */
    public ReturnData topDepartment(){
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from sys_department where parentDepartmentId is null or parentDepartmentId=''";
        List<Record> list=Db.find(sql);
        returnData.setData(list);
        return returnData;
    }
    /**
     * 查询所有部门
     */
    public ReturnData department(){
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from sys_department ";
        List<Record> list=Db.find(sql);
        returnData.setData(list);
        return returnData;
    }
    /**
     * 保存部门
     */
    public ReturnData saveDepartment(String id,String name,String userId){
        ReturnData returnData=new ReturnData();
        boolean sa=false;
        if ("".equals(id) || id==null){
            Record record=new Record().set("id",UtilUUID.getUUID()).set("name",name)
                    .set("userId",userId);
            sa=Db.save("sys_department","id",record);
        }else {
            Record record=new Record().set("id",id).set("name",name).set("userId",userId);
            sa=Db.update("sys_department","id",record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }

    /**
     * 权限分类列表
     */
    public ReturnData rpermissionTypeService(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from sys_permission_type";
        List<Record> recordList=Db.find(sql);
        if (recordList.size()>0){
            returnData.setData(recordList);
        }
        return returnData;
    }
    /**
     * 保存权限分类
     */
    public ReturnData saveRpermissionTypeService(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        String id=map.get("id")[0];
        String name=map.get("name")[0].trim();
        Record record=new Record().set("type_name",name);
        boolean re=false;
        if ("".equals(id)){
            re=Db.save("sys_permission_type",record);
        }else {
            record.set("id",id);
            re=Db.update("sys_permission_type","id",record);
        }
        returnData.setCode(re+"");
        returnData.setData(record);
        return returnData;
    }
    /**
     * 删除权限分类
     */
    public ReturnData delRpermissionTypeService(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        String id=map.get("id")[0];
        String sql="DELETE from sys_permission_type where id='"+id+"'";
        int del=Db.delete(sql);
        returnData.setData(del);
        return returnData;
    }
    /**
     * 部门所具有的角色列表
     */
    public Map departmentRoleListService(String id){
        String sql="SELECT\n" +
                "\tsd.sys_department_id AS id,\n" +
                "\tsr.`name`\n" +
                "FROM\n" +
                "\tsys_department_role sd\n" +
                "LEFT JOIN sys_role sr ON sd.sys_role_id = sr.`name`\n" +
                "WHERE\n" +
                "\tsd.sys_department_id ="+id+"";
        List<Record> list=Db.find(sql);
        Map map=new HashMap();
        map.put("total",list.size());
        map.put("data",list);
        return map;
    }


    /**
     * 保存管理员信息
     */
    public ReturnData saveAdminService(Map<String,String[]> map,String userId){
        ReturnData returnData=new ReturnData();
        boolean sa=false;
        String id=map.get("id")[0];
        String userCode=map.get("userCode")[0];
        String userName=map.get("userName")[0];
        String password=map.get("password")[0];
        String phone=map.get("phone")[0];
        String type=map.get("type")[0];
        Record userRecord=cache.get(userId);
        String adminUserId=userRecord.getStr("adminUserId");
        adminUserId=type=="1"?userRecord.getStr("id"):adminUserId;
        type="0".equals(userRecord.getStr("type"))?"1":"2";
        String salt=UtilUUID.getOrderIdByUUId();
        if ("".equals(id) || "null".equals(id) ||"null".equals(id)){
            Record record=new Record();
            record.set("id",UuidUtil.get32UUID()).set("locked","0").set("type",type).set("adminUserId",adminUserId);
            record.set("password",MD5.md5(userCode
                    +salt+password)).set("userName",userName).set("salt",salt).set("userCode",userCode)
            .set("phone",phone);
            sa=Db.save("sys_user","id",record);
        }else {
            Record record=new Record().set("locked","0");
            record.set("password",MD5.md5(userCode
                    +salt+password)).set("userName",userName).set("salt",salt).set("userCode",userCode).set("id",id)
                    .set("phone",phone);;
            sa=Db.update("sys_user","id",record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
        }
        public ReturnData getAdmin(Map<String,String[]> map){
            ReturnData returnData=new ReturnData();
            boolean sa=false;
            String userCode=map.get("userCode")[0];
            String sql = "select id from sys_user where userCode='"+userCode+"'";
            List<Record> recordList = Db.find(sql);
            if(recordList.size()==0){
                sa = true;
            }
            returnData.setCode(String.valueOf(sa));
            return returnData;
        }

    /**
     * 保存用户权限
     * @return
     */
    public ReturnData  saveUserPermission(Map<String,String[]> map){
        ReturnData data = new ReturnData();
        String[] idsChecked= map.get("ids[]");//选中的
        String userId=map.get("userId")[0];
        String type=map.get("type")[0];
        List<Record> recordList=new ArrayList<>();
        if ("user".equals(type)){//给用户授权
            String del="DELETE from sys_user_permission where sys_user_id='"+userId+"'";
            Db.delete(del);
            if (idsChecked!=null){//非空
                for (int i=0;i<idsChecked.length;i++){
                    Record record=new Record().set("sys_user_id",userId).set("sys_permission_id",idsChecked[i]);
                    recordList.add(record);
                }
                int[] sa=Db.batchSave("sys_user_permission",recordList,recordList.size());
            }else {

            }
        }
        data.setData("true");
        return data;
    }

    public ReturnData saveAuthorizationButtonService(String id,String name,String url,String parentid){
        ReturnData returnData=new ReturnData();
        boolean sa=false;
        if("".equals(id) || id==null || "null".equals(id)){//新增按钮
            Record record=new Record().set("id",UtilUUID.getUUID()).set("name",name).set("url",url)
                    .set("parentid",parentid).set("type","button");
            sa=Db.save("sys_permission","id",record);
        }else {
            Record record=new Record().set("id",id).set("name",name).set("url",url)
                    .set("parentid",parentid).set("type","button");
            sa=Db.update("sys_permission","id",record);
        }
        returnData.setCode(String.valueOf(sa));
        return returnData;
    }



    /**
     * 查询所有权限
     * @param type
     * @param userId
     * @return
     */
    public ReturnData findAllResource(String type,String userId) {
        ReturnData data = new ReturnData();
        List<Map<String,List<Map<String,String>>>> mapList = new ArrayList<>();
        Map returnMap=new LinkedHashMap();
        try {
            List<Record> record1 = new ArrayList<>(); //list 父权限
            Record userRecord=cache.get(userId);
            List<Record> permissionList=userRecord.get("permission");
            for (int i=0;i<permissionList.size();i++){//遍历出所有的父类
                String parentid=permissionList.get(i).getStr("parentid");
                if (parentid==null || "0".equals(parentid)){
                    record1.add(permissionList.get(i));
                }
            }
            permissionList.removeAll(record1);
            for (int i=0;i<record1.size();i++){ //组装子权限
                List<Record> records = new ArrayList<>();//二级权限
                /*record1.get(i).set("second",new ArrayList<Record>());*/
                    records.add(record1.get(i));
                    String name=record1.get(i).getStr("name");
                    String id=record1.get(i).getStr("id");
                    for (int j=0;j<permissionList.size();j++){
                        List<Record> recordList=new ArrayList<>();
                        for(int k=0;k<permissionList.size();k++){//遍历出按钮
                            String secondId=permissionList.get(j).getStr("id");
                            if (secondId.equals(permissionList.get(k).getStr("parentid"))){//按钮列表
                                recordList.add(permissionList.get(k));
                            }
                        }
                        permissionList.get(j).set("button",recordList);
                        if (id.equals(permissionList.get(j).getStr("parentid"))){
                            permissionList.get(j).set("button",new ArrayList<Record>());
                            records.add(permissionList.get(j));
                        }

                    }
                returnMap.put(name,records);
            }
            data.setData(returnMap);
        }catch (Exception e){
            Syslog.error(e);
            Syslog.error("获取权限数据异常-----"+e);
        }
        return data;
    }

    /**
     *  用户列表
     *
     */
    public List<Record> adminListService(int currentPage,int size,
                                         String userName,String userCode,
                                         String type,
                                         String userId){
        String sql="SELECT *from sys_user where  adminUserId = '"+userId+"'";
        if ("".equals(userCode)==false && "null".equals(userCode)==false && userCode!=null){
            sql+=" and userCode like '%"+userCode+"%'";
        }
        if ("".equals(userName)==false && "null".equals(userName)==false && userName !=null){
            sql+=" and userName like '%"+userName+"%'";
        }
        PageUtil<Record>  pageUtil=new PageUtil<>(currentPage,size,sql);
        List<Record> list=pageUtil.getList();
        return list;
    }


    /**
     * 按钮权限
     */
    public ReturnData buttonAjaxService(String id){
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from sys_permission WHERE type='button'  and parentid='"+id+"'";
        List<Record> recordList=Db.find(sql);
        returnData.setData(recordList);
        return returnData;
    }


    /**
     * 新增角色并赋予角色权限
     * @param map
     * @return
     */

    public ReturnData addRoleInfo(Map<String,String[]> map,String userId) throws Exception{
        String adminUserId = userId;
        ReturnData data = new ReturnData();
        String name = map.get("name")[0];
        Record record = new Record();
        String roleId = UtilUUID.getUUID();
        record.set("name",name)
                .set("id",roleId)
                .set("available","1")
                .set("createTime",new Date())
                .set("adminUserId",adminUserId);
        boolean isSuccess=Db.save("sys_role",record);
        /*添加 sys_user_role 中间表 */
        Record userRole=new Record().set("id",UtilUUID.getUUID()).set("sys_user_id",userId).set("sys_role_id",roleId);
        boolean sa=Db.save("sys_user_role","id",userRole);
        if(isSuccess && sa){
            data.setData("true");
        }else {
            data.setData("false");
            throw new Exception();
        }
        return data;
    }
    /**
     * 角色列表
     * @return
     */
    public ReturnData roleList(Map<String,String[]> map,String userId) {
        ReturnData data = new ReturnData();
        try {
            Record userRecord=cache.get(userId);
            String adminUserId = userRecord.getStr("adminUserId");
            int curr=Integer.parseInt(map.get("currentPage")[0]);//当前页
            int size=Integer.parseInt(map.get("size")[0]);
            String sql = "SELECT a.id, a.`name`, IFNULL(group_concat(c.`name`), '') as permission FROM sys_role a \n" +
                    "LEFT JOIN sys_role_permission b ON a.id = b.sys_role_id\n" +
                    "LEFT JOIN sys_permission c ON b.sys_permission_id = c.id\n" +
                    "WHERE a.adminUserId='"+userId+"'  GROUP BY `name`, id order by a.createTime DESC";
            PageUtil<List<Record>> pageUtil= new PageUtil<>(curr, size, sql);
            data.setData(pageUtil);
            return data;
        }catch (Exception e){
            Syslog.error("查询权限异常--"+e);
        }
        return data;
    }
    /**
     * 删除角色
     * @param map
     * @return
     */
    public ReturnData roleDel(Map<String, String[]> map,String userId) throws Exception{
        ReturnData data = new ReturnData();
        String rid = map.get("rid")[0];
        String sql0 ="DELETE FROM sys_role where id ='"+rid+"'";
        int aa = Db.delete(sql0);
        String sql = "SELECT COUNT(*) as number FROM sys_role_permission a WHERE a.sys_role_id ='"+rid+"'";
        int num = Db.queryInt(sql);
        String sql2 = "DELETE FROM sys_role_permission WHERE sys_role_id ='"+rid+"'";
        int ss = Db.delete(sql2);
        String sql3 = "DELETE FROM sys_user_role  WHERE sys_user_id='"+userId+"' AND sys_role_id='"+rid+"'";
        int ss2=Db.delete(sql3);
        if(aa==1 && num == ss && ss2==1){
            data.setData("success");
        }else {
            data.setData("false");
            throw new Exception();
        }
        return data;
    }




    /**
     * 角色列表
     * @return
     */
    public ReturnData roleList() {
        ReturnData data = new ReturnData();
        try {
            String sql = "SELECT a.id, a.`name`, IFNULL(group_concat(c.`name`), '') as permission FROM sys_role a \n" +
                    "LEFT JOIN sys_role_permission b ON a.id = b.sys_role_id\n" +
                    "LEFT JOIN sys_permission c ON b.sys_permission_id = c.id\n" +
                    "WHERE 1=1  GROUP BY `name`, id order by a.createTime DESC";
            data.setData(Db.find(sql));
            return data;
        }catch (Exception e){
            Syslog.error("查询权限异常--"+e);
        }
        return data;
    }

    /**
     *根据当前用户ID查询出树形结构的权限tree
     */
    public List<Record> treePermissionByUserId(String userId){
//        String sqlOne="";
//        if ("1".equals(userId)){
//            sqlOne="SELECT * from sys_permission where  parentid ='0' GROUP BY id " ;
//        }else {
//            sqlOne="SELECT spe.id from sys_permission   spe LEFT JOIN sys_user_permission sup on spe.id=sup.sys_permission_id \n" +
//                    "where sup.sys_user_id='"+userId+"' and  spe.parentid ='0' GROUP BY spe.id "  ;
//        }
//        List<Record> onePermission=Db.find(sqlOne);

        Record record=cache.get(userId);
        List<Record> permission=record.get("permission");
        List<Record> onePermission=new ArrayList<>();
        List<Record> twoPermission=new ArrayList<>();
        /*遍历出所有的一级权限*/
        for (int i=0;i<permission.size();i++){//遍历一级权限
            Record temp=permission.get(i);
            //String id=temp.getStr("id");
            if ("0".equals(temp.getStr("parentid"))==false){
                twoPermission.add(temp);
            }else {
                onePermission.add(temp);
            }
        }

        for (int i=0;i<onePermission.size();i++){//遍历一级权限
            Record temp=onePermission.get(i);
            String id=temp.getStr("id");
            List<Record> tempTwoList=new ArrayList<>();
            //twoPermission
            for (int j=0;j<twoPermission.size();j++){
                Record tempTwo=onePermission.get(i);
                if (tempTwo.getStr("parentid")==id){
                    tempTwoList.add(tempTwo);
                }
            }
            temp.set("twoPermission",tempTwoList);
            onePermission.set(i,temp);
        }
        return onePermission;
    }



    /**
     *根据当前用户ID权限ID查询出对应的权限
     */
    public List<Record> getPermissionByUserIdAndPermissionId(String userId,String permissionId){
//        String sqlOne="";
//        if ("1".equals(userId)){
//            sqlOne="SELECT * from sys_permission spe where 1=1  " ;
//        }else {
//            sqlOne="SELECT spe.* from sys_permission   spe LEFT JOIN sys_user_permission sup on spe.id=sup.sys_permission_id \n" +
//                    "where sup.sys_user_id='"+userId+"' ";
//        }
//        if (permissionId!=null && "".equals(permissionId)==false){
//            sqlOne+=" and spe.parentid='"+permissionId+"'";
//        }else {
//            sqlOne+=" and  spe.parentid is null or spe.parentid ='0'";
//        }
        Record record=cache.get(userId);
        List<Record> permission=record.get("permission");
        List<Record> onePermission=new ArrayList<>();

        /*遍历出所有的一级权限*/
        for (int i=0;i<permission.size();i++){//遍历一级权限
            Record temp=permission.get(i);
            if (permissionId.equals(temp.getStr("parentid"))){
                onePermission.add(temp);
            }else {

            }
        }
        return onePermission;
    }





    /**
     * 根据角色Id查询出具有的权限
     */
    public List<Record> selectPermissionByRoleId(String roleId){
        String sql="SELECT spe.* from sys_permission   spe LEFT JOIN sys_role_permission srp on srp.sys_permission_id=spe.id\n" +
                "WHERE srp.sys_role_id='"+roleId+"'  GROUP BY spe.id ";
        List<Record> list=Db.find(sql);
        cache.setex(roleId+"permission",60*30,list);
        return list;
    }
    public ReturnData settingUserOrRolePerssionService(String id,String type,String primissionId,boolean state){
        ReturnData returnData=new ReturnData();
        if ("user".equals(type)){//如果是用户
            if(state){//如果是授予权限
                String sql="SELECT *from sys_user_permission where sys_permission_id='"+
                        primissionId+"' and sys_user_id='"+id+"'";
                Record record=Db.findFirstByCache("oneDay",MD5.md5(sql),sql);
                if (record!=null){//已有权限
                    returnData.setCode("000000");
                }else {
                    record=new Record().set("sys_user_id",id).set("sys_permission_id",primissionId);
                    boolean save=Db.save("sys_user_permission",record);
                    if (save){
                        returnData.setCode("000000");
                    }else {
                        returnData.setCode("111111");
                        returnData.setMsg("保存失败");
                    }
                }
            }else {//删除权限
                String sql=" delete from `sys_user_permission` where sys_user_id ='"+id+"' and sys_permission_id='"+primissionId+"'";
                int del=Db.delete(sql);
                if (del>0){
                    returnData.setCode("000000");
                    /*删除 该权限下 所有的子权限*/
                    String sonSql="SELECT id from sys_permission where parentid='"+primissionId+"'";
                    List<Record> list=Db.find(sonSql);
                    for (int i=0;i<list.size();i++){
                        Record temp=list.get(i);
                        String sonPrimissionId=temp.getStr("id");
                        String delSonSql=" delete from `sys_user_permission` where sys_user_id ='"+id+"' and sys_permission_id='"+sonPrimissionId+"'";
                        int delInt=Db.delete(delSonSql);
                        Syslog.info("删除子权限"+delInt);
                    }
                }else {
                    returnData.setCode("111111");
                    returnData.setMsg("保存失败");
                }
            }
        }else {//角色操作
            if (state){//开通权限
                String sql="SELECT *from sys_role_permission where sys_role_id='"+id+"' and sys_permission_id='"+primissionId+"'";
                Record record=Db.findFirstByCache("oneDay",MD5.md5(sql),sql);
                if (record!=null){//已有权限
                    returnData.setCode("000000");
                }else {
                    record=new Record().set("sys_role_id",id).set("sys_permission_id",primissionId);
                    boolean sa=Db.save("sys_role_permission",record);
                    if (sa){
                        returnData.setCode("000000");
                    }else {
                        returnData.setCode("111111");
                        returnData.setMsg("保存失败");
                    }
                }
            }else {//关闭权限
                String sql=" DELETE from sys_role_permission where sys_role_id='"+id+"' and sys_permission_id='"+primissionId+"'";
                int de=Db.delete(sql);
                if (de>0){
                    returnData.setCode("000000");
                      /*删除 该权限下 所有的子权限*/
                    String sonSql="SELECT id from sys_permission where parentid='"+primissionId+"'";
                    List<Record> list=Db.find(sonSql);
                    for (int i=0;i<list.size();i++){
                        Record temp=list.get(i);
                        String sonPrimissionId=temp.getStr("id");
                        String delSonSql=" DELETE from sys_role_permission where sys_role_id='"+id+"' and sys_permission_id='"+sonPrimissionId+"'";
                        Db.delete(delSonSql);
                    }
                }else {
                    returnData.setCode("111111");
                    returnData.setMsg("保存失败");
                }
            }
        }
        return returnData;
    }

    /**
     * 查询出一级权限(当前用户具有的)
     * @param userId
     * @return
     */
    public List<Record> onePermissionService(String userId){
        List<Record> list=selectPermissionByUserId(userId);
        List<Record> resultList=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Record temp=list.get(i);
            String parentid=temp.getStr("parentid");
            if ("0".equals(parentid)){
                resultList.add(temp);
            }
        }
        return resultList;
    }


    /**
     * 根据一级权限查询出二级权限(当前用户具有的)
     * @param permissionId
     * @param userId
     * @return
     */
    public List<Record> twoPermissionService(String permissionId,String userId){
        List<Record> list=selectPermissionByUserId(userId);
        List<Record> resultList=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Record temp=list.get(i);
            String parentid=temp.getStr("parentid");
            if (parentid.equals(permissionId)){
                resultList.add(temp);
            }
        }
        return resultList;
    }

    /**
     * 根据上级权限id 和用户id 查询出三级按钮
     * @param permissionId
     * @param userId
     * @return
     */
    public List<Record> threePermissionService(String permissionId,String userId){
        List<Record> list=selectPermissionByUserId(userId);
        List<Record> resultList=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Record temp=list.get(i);

            String parentid=temp.getStr("parentid");
            if (parentid.equals(permissionId)){
                Syslog.info(temp.toJson());
                resultList.add(temp);
            }
        }
        return resultList;
    }





    /**
     * 根据用户Id查询出具有的权限
     */
    public List<Record> selectPermissionByUserId(String userId){
        String sql="";
        if ("1".equals(userId)){
            sql="SELECT * from sys_permission";
        }else {
            sql="SELECT spe.id, spe.name,spe.type,spe.url,spe.percode,spe.parentid, spe.parentids,spe.sortstring,  spe.available    from sys_permission   spe LEFT JOIN sys_user_permission sup on spe.id=sup.sys_permission_id \n" +
                    "where sup.sys_user_id='"+userId+"'";
            String roleSql="SELECT spe.id, spe.name,spe.type,spe.url,spe.percode,spe.parentid, spe.parentids,spe.sortstring,  spe.available  from sys_permission spe LEFT JOIN sys_role_permission srp on srp.sys_permission_id=spe.id\n" +
                    "LEFT JOIN sys_role sr on sr.id=srp.sys_role_id LEFT JOIN sys_user_role sur on sur.sys_role_id=sr.id\n" +
                    "WHERE sur.sys_user_id='"+userId+"' GROUP BY spe.id";
            sql=sql+ " union "+ roleSql;
            sql=" select * from ("+sql+") rr group by rr. id";
        }
        List<Record> list=Db.find(sql);//用户个人的
        cache.setex(userId+"permission",60*30,list);
        return list;
    }
    /**
     * 保存权限
     */
    public ReturnData saveRoleOrUserPermissionService(Map<String,String[]> map){
        ReturnData returnData=new ReturnData();
        boolean result=true;
        String type=map.get("type")[0];
        String id=map.get("id")[0];
        String ids=map.get("ids")[0];
        String[] idsArr=ids.split(",");
        List<String> idsList= Arrays.asList(idsArr);//选中的权限ID
        String permissionId=map.get("permissionId")[0];
        if ("role".equals(type)){//角色权限]
            //查出当前角色所拥有的权限
            //String sql="SELECT  sys_role_id,sys_permission_id from sys_role_permission where sys_role_id='"+id+"'";
            //nowPermission=Db.find(sql);
            List<Record> insertList=new ArrayList<>();
            for (int i=0;i<idsList.size();i++){
                String tempId=idsList.get(i);
                Record tempRecord=new Record();
                tempRecord.set("sys_role_id",id);
                tempRecord.set("sys_permission_id",tempId);
                insertList.add(tempRecord);
            }

            String delSql="DELETE\n" +
                    "FROM\n" +
                    "\tsys_role_permission\n" +
                    "WHERE\n" +
                    "\tsys_role_id = '"+id+"'\n" +
                    " and sys_permission_id in ( SELECT id from sys_permission where parentid='"+permissionId+"' )";
            int delInt=Db.delete(delSql);//删除所有角色权限中间表
            Syslog.info("删除了 "+delInt+"数据");
            int insertArr[]=Db.batchSave("sys_role_permission",insertList,insertList.size());
            Syslog.info(insertArr);
            //执行删除
            for (int i=0;i<insertArr.length;i++){
                if (insertArr[i]==0){
                    result=false;
                }
            }
        }else if("user".equals(type)){
            //查询当前用户所有的权限
//            String sql="SELECT sys_user_id,sys_permission_id from sys_user_permission where sys_user_id='"+id+"'";
//            nowPermission=Db.find(sql);
            List<Record> insertList=new ArrayList<>();
            for (int i=0;i<idsList.size();i++){
                String tempId=idsList.get(i);
                Record tempRecord=new Record();
                tempRecord.set("sys_user_id",id);
                tempRecord.set("sys_permission_id",tempId);
                insertList.add(tempRecord);
            }
            String delSql="DELETE from sys_user_permission where sys_user_id='"+id+"' " +
                    " and sys_permission_id in ( SELECT id from sys_permission where parentid='"+permissionId+"' ) ";
            int delInt=Db.delete(delSql);//删除所有角色权限中间表
            Syslog.info("删除了 "+delInt+"数据");
            int insertArr[]=Db.batchSave("sys_user_permission",insertList,insertList.size());
            Syslog.info(insertArr);
            //执行删除
            for (int i=0;i<insertArr.length;i++){
                if (insertArr[i]==0){
                    result=false;
                }
            }

        }
        if (result){
            returnData.setCode("000000");
            returnData.setMsg("保存成功");
        }else {
            returnData.setCode("111111");
            returnData.setMsg("保存失败");
        }
        return returnData;
    }


    /**
     * 删除角色
     * @param map
     * @return
     */
    @Before(Tx.class)
    public ReturnData roleDel(Map<String, String[]> map) throws Exception{
        ReturnData data = new ReturnData();
        String rid = map.get("rid")[0];
        String sql0 ="DELETE FROM sys_role where id ='"+rid+"'";
        int aa = Db.delete(sql0);
        String sql = "SELECT COUNT(*) as number FROM sys_role_permission a WHERE a.sys_role_id ='"+rid+"'";
        int num = Db.queryInt(sql);
        String sql2 = "DELETE FROM sys_role_permission WHERE sys_role_id ='"+rid+"'";
        int ss = Db.delete(sql2);
        if(aa==1 && num == ss){
            data.setData("success");
        }else {
            data.setData("false");
        }
        return data;
    }


    /**
     * 查询角色信息
     * @return
     */
    public ReturnData findRoleInfo(String rid, String userId) {
        ReturnData data = new ReturnData();
        Map returnMap=new LinkedHashMap();
        List<Record> record1 = new ArrayList<>();
        Map map1=new HashMap();
        try {

            String sql0 = "SELECT a.`name` FROM sys_role a WHERE a.id='"+rid+"'";
            String roleName = Db.queryStr(sql0);
            map1.put("returnMap",returnMap);
            map1.put("roleName",roleName);
            data.setData(map1);
        }catch (Exception e){
            Syslog.error("查询角色信息异常------"+e);
        }
        return data;
    }

    /**
     * 修改角色
     * @param map
     * @return
     */
    public ReturnData updateRole(Map<String, String[]> map) {
        ReturnData data = new ReturnData();
        String rid = map.get("rid")[0];
        String name = map.get("name")[0];
        int ss2=0;
        String sql2 = "update sys_role set name='"+name+"' where id='"+rid+"'";
        ss2=Db.update(sql2);
        if(ss2==1){
            data.setData("success");
            return data;
        }else{
            data.setData("fail");
            return data;
        }

    }
    /**
     * 根据 用户id 查询对应管理员下的所有角色
     */
    public List<Record> getRolesByAdminUserId(String id){
        String sql="SELECT  sr.* from sys_role sr where sr.adminUserId='"+id+"' ";
        List<Record> list=Db.find(sql);
        return list;
    }
    /**
     * 根据用户id查询用户对应的角色
     */
    public List<Record> getRolesByUserId(String id){
        String sql="SELECT sro.* from sys_role sro LEFT JOIN sys_user_role sur on sro.id=sur.sys_role_id where sur.sys_user_id='"+id+"'";
        List<Record> list=Db.find(sql);
        return list;
    }
    /**
     * 保存用户的角色修改
     */
    public ReturnData saveUserRoleService(Map<String,String[]> map,String adminUserId) throws Exception {
        String id=map.get("id")[0];
        String ids=map.get("ids")[0];
        String[] strArr=ids.split(",");
        ReturnData returnData=new ReturnData();
        boolean result=true;
        List<String> idsList=Arrays.asList(strArr);
        /*查询当前用户的角色*/
        List<Record> nowRoles=getRolesByUserId(adminUserId);//当前管理员下的角色
        List<Record> insertList=new ArrayList<>();
        for (int i=0;i<idsList.size();i++){
            String tempId=idsList.get(i);
            Record tempRecord=new Record();
            tempRecord.set("id",UuidUtil.get32UUID());
            tempRecord.set("sys_user_id",id);
            tempRecord.set("sys_role_id",tempId);
            insertList.add(tempRecord);
        }
        /*删除所有的用户-角色中间表*/
        String delSql="DELETE from sys_user_role where sys_user_id='"+id+"'";
        Db.delete(delSql);
        /*添加到新的用户-角色中间表*/
        int[] insertArr=Db.batchSave("sys_user_role",insertList,insertList.size());
        for (int i=0;i<insertArr.length;i++){
            int k=insertArr[i];
            if (k!=1){
                result=false;
            }
        }
        if (result==false){
            returnData.setCode("111111");
            returnData.setMsg("保存失败");
            throw new Exception();
        }else {
            returnData.setCode("000000");
            returnData.setMsg("保存成功");
        }
        return returnData;
    }









    /**
     * 根据用户ID查询用户权限  key-value形式
     * @param userId
     * @return
     */
    public ReturnData userPermissionByUserId(String userId){
        ReturnData returnData=new ReturnData();
        String permissionSql="SELECT spi.percode, spi.url,spi.parentid,spi.id,spi.name from sys_permission spi\n" +
                "LEFT JOIN sys_user_permission sup\n" +
                "on spi.id=sup.sys_permission_id\n" +
                "LEFT JOIN sys_user su ON\n" +
                "sup.sys_user_id=su.id\n" +
                "WHERE su.id='"+userId+"'";//查询所拥有的权限
        List<Record> permissionList=Db.find(permissionSql);
        for (int i=0;i<permissionList.size();i++){
            String url=permissionList.get(i).getStr("url");
            int a=url.indexOf("?");
            a=a==-1?url.length():a;
            url=url.substring(0,a);
            permissionList.get(i).set("url",url);
        }
        returnData.setData(permissionList);
        return returnData;
    }


    /**
     * 根据部门ID查询部门权限  key-value形式
     * @param id
     * @return
     */
    public ReturnData departmentPermissionById(String id){
        ReturnData returnData=new ReturnData();
        String permissionSql="SELECT spi.percode, spi.url,spi.parentid,spi.id,spi.name from sys_permission spi\n" +
                "LEFT JOIN sys_user_permission sup\n" +
                "on spi.id=sup.sys_permission_id\n" +
                "LEFT JOIN sys_user su ON\n" +
                "sup.sys_user_id=su.id\n" +
                "WHERE su.id='"+id+"'";//查询所拥有的权限
        List<Record> permissionList=Db.find(permissionSql);
        for (int i=0;i<permissionList.size();i++){
            String url=permissionList.get(i).getStr("url");
            int a=url.indexOf("?");
            a=a==-1?url.length():a;
            url=url.substring(0,a);
            permissionList.get(i).set("url",url);
        }
        returnData.setData(permissionList);
        return returnData;
    }


    /**
     * 上级用户给下级用户授权  下级是否拥有该权限
     * @param one  上级权限集合
     * @param two  下级权限集合
     * @return
     */
    public ReturnData authorizationService(ReturnData one,ReturnData two){
        ReturnData returnData=new ReturnData();
        List<Record> twoList= (List<Record>) two.getData();
        Map<String,List<Record>> oneList= (Map<String, List<Record>>) one.getData();
        for (Map.Entry<String,List<Record>> entry : oneList.entrySet()){
            List<Record> recordList=entry.getValue();
            for (int i=0;i<recordList.size();i++){
                String url=recordList.get(i).getStr("url");
                int b=url.indexOf("?");
                b=b==-1?url.length():b;
                url=url.substring(0,b);
                recordList.get(i).set("url",url);
                if (twoList.contains(recordList.get(i))){//如果该人所有的权限是否包含该权限
                    recordList.get(i).set("checked","checked");//设置为选中状态
                }
            }
        }
        returnData.setData(oneList);
        return returnData;
    }
    /**
     * 根据用户userId查询出管理员Id
     *
     */
    public String getAdminUserId(String userId){
        String sql="SELECT *from sys_user where id='"+userId+"'";
        Record record=Db.findFirstByCache("adminUser",MD5.md5(sql),sql);
        String adminUserId=record.getStr("adminUserId");
        adminUserId="1".equals(adminUserId)?record.getStr("id"):adminUserId;
        return adminUserId;
    }
    public ReturnData goOrgNumberEditService(String adminUserId){
        String sql="SELECT orgNumber from sys_user where id='"+adminUserId+"'";
        int all=Db.queryInt(sql);
        String countSql="SELECT COUNT(*) from yx_org WHERE adminUserId='"+adminUserId+"'";
        int count=Db.queryInt(countSql);
        ReturnData returnData=new ReturnData();
        Map map=new HashMap();
        map.put("all",all);
        map.put("count",count);
        returnData.setData(map);
        returnData.setMsg("保存成功");
        return returnData;
    }
    /**
     * 给代理商增加机构数量
     */
    public synchronized ReturnData addOrgNumberService(String adminUserId,int addNumber){
        ReturnData returnData=new ReturnData();
        String sql="UPDATE sys_user SET orgNumber=orgNumber+"+addNumber+" where id='"+adminUserId+"'";
        int up=Db.update(sql);
        if (up==1){
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        }else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    public Map adminActivityList(Map<String,String[]> parmap){
        String page=parmap.get("page")[0];
        String limit=parmap.get("limit")[0];
        String activityName=parmap.get("activityName")[0].trim();
        String orgName=parmap.get("orgName")[0].trim();
        String personTel=parmap.get("personTel")[0].trim();
        String sql="SELECT ya.id, ya.name as activityName ,ya.talkMoney/100 as talkMoney ,ya.createTime,\n" +
                "case ya.type\n" +
                "when ya.type=0 then '支付参与活动'\n" +
                "when ya.type=1 then '填写信息参与活动'\n" +
                "ELSE '无需操作参与活动' \n" +
                "end as type,\n" +
                "yo.name as orgName ,yo.person ,yo.personTel,sus.userCode,sus.userName\n" +
                " from yx_activity ya LEFT JOIN yx_org yo on ya.orgId=yo.id LEFT JOIN sys_user sus on yo.adminUserId=sus.id\n" +
                "where 1=1 \n" ;
        if (activityName!=""){
            sql+=" and ya.name like '%"+activityName+"%' ";
        }
        if (orgName!=""){
            sql+=" and yo.name like '%"+orgName+"%' ";
        }
        if (personTel!=""){
            sql+=" and yo.personTel = '"+personTel+"' ";
        }
        sql+=" ORDER BY ya.createTime desc ";
        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(limit) ,sql);
        int code=0;
        String msg="请求成功";
        int count=pageUtil.getTotalRows();
        Map map=new HashMap();
        map.put("code",code);
        map.put("msg",msg);
        map.put("count",count);
        map.put("data",pageUtil.getList());
        return map;
    }






}
